﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using IdentityModel.Client;
using Microsoft.Extensions.Configuration;
using JWT.Algorithms;
using Volo.Abp.Json;
using JWT;
using JWT.Serializers;

namespace taigu
{
    /*
     * 文件名:Ids4Service
     * 功能：ids4服务管理
     * 创建时间：2021-11-15
     * 作者:gavin
     */
    /// <summary>
    /// ids4服务注册类
    /// </summary>
    public class Ids4Service : IIds4Service
    {
        private IConfiguration _configuration;
        public Ids4Service(IConfiguration configuration)
        {
            this._configuration = configuration;
        }
        /// <summary>
        /// 获取系统token
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <returns></returns>
        public async Task<string> GetIdsTokenAsync(string userName, string userPwd)
        {
            var client = new HttpClient();
            var idsTokenUrl = this._configuration.GetSection("AuthServer:Authority").Value;
            var AppClientId = this._configuration.GetSection("AuthServer:AppClientId").Value;
            var AppClientSecret = this._configuration.GetSection("AuthServer:AppClientSecret").Value;
            // var disco = client.GetDiscoveryDocumentAsync(idsTokenUrl);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("userId", "1");
            var tokenResponse = await client.RequestPasswordTokenAsync(
                new PasswordTokenRequest
                {
                    Address = idsTokenUrl + "/connect/token",//disco.Result.TokenEndpoint,
                    ClientId = AppClientId,
                    ClientSecret = AppClientSecret,
                    UserName = userName,
                    Password = userPwd,
                    Parameters = dic
                }
                );

            if (tokenResponse.IsError)
            {
                return string.Empty;
            }
          //  this.DecodeJwtToken(tokenResponse.AccessToken);
            return tokenResponse.AccessToken;
        }

        [Obsolete]
        public string DecodeJwtToken(string jwtToken)
        {
            var AppClientSecret = this._configuration.GetSection("AuthServer:AppClientSecret").Value;
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            JWT.IJsonSerializer serializer = new JsonNetSerializer();
            JWT.IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

            var json = decoder.Decode(jwtToken, AppClientSecret, verify: false);

            // await Task.Run(() => { });
            return json;
        }
    }
}
